package org.invigorare.auctions;

import static org.invigorare.auctions.data.SaleDataOpener.*;
import org.invigorare.auctions.data.SaleDataOpener;
import org.invigorare.auctions.widgets.SaleItemCursorAdapter;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;

public class AuctionSaleList extends ListActivity {
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auction_sale_list);
        
        populateList();
        
    }
    
    final static String[] colsToDisplay = new String[] {
    	SALE_TIMESTAMP,
    	SELLER_LICENSE,
    	BUYER_LICENSE,
    	SALE_WEIGHT,
    	SALE_RATE,
    	SALE_TOTAL,
    	SALE_PRODUCE_ID,
    	_IS_SYNCED
    };

    final static int[] viewsToDisplay = new int[] {
    	R.id.saleitem_label_sale_date,
    	R.id.saleitem_label_seller_info,
    	R.id.saleitem_label_buyer_info, 
       	R.id.saleitem_contents_weight,
    	R.id.saleitem_contents_rate,
    	R.id.saleitem_contents_totalSale,
    	R.id.saleitem_contents_produceName,
    	R.id.saleitem_isSynced
    };
    
    Cursor cursor;
    SQLiteDatabase db;
    
    private void populateList() {
    	
    	db = SaleDataOpener.getReadableDb(getApplicationContext());
    	cursor = db.query(SaleDataOpener.SALE_TABLE_NAME, null, null, null, null, null, null);

    	setListAdapter(new SaleItemCursorAdapter(this, R.layout.auction_sale_list_item, cursor, colsToDisplay, viewsToDisplay));
    	
    	// cursor.close() called in onDestroy() -- leaving the cursor open for the ListAdapter
    }
    
    @Override
    public void onDestroy() {

    	if (cursor != null)
    		cursor.close();
    	
    	if (db != null)
    		db.close();
    	
    	super.onDestroy();
    }
    
}
